/* 
 * File:   TAllocationBlock.cpp
 * Author: dvdemon
 * 
 * Created on July 28, 2015, 9:17 AM
 */

#include "TAllocationBlock.h"
#include <iostream>

TAllocationBlock::TAllocationBlock(uint64_t size, uint64_t count) : _size(size), _count(count) {
    _used_blocks = (char*) malloc(_size * _count);
    _free_blocks = (void**) malloc(sizeof (void*)*_count);

    for (uint64_t i = 0; i < _count; i++) 
        _free_blocks[i] = _used_blocks + i * _size;
    _free_count = _count;
    std::cout << "TAllocationBlock: Memory init" << std::endl;
}

 void *TAllocationBlock::allocate() {
    void *result = nullptr;

    if (_free_count > 0) {
        result = _free_blocks[--_free_count];
        //std::cout << "TAllocationBlock: Allocate " << (_count-_free_count) << " of " << _count << " Address:" << result << std::endl;
    } else {
        std::cout << "TAllocationBlock: No memory exception :-)" << std::endl;
    }

    return result;
}

 void TAllocationBlock::deallocate(void *pointer) {
    //std::cout << "TAllocationBlock: Deallocate block "<< std::endl;

    _free_blocks[_free_count++] = pointer;
    //  _free_count ++;
}

bool TAllocationBlock::has_free_blocks() {
    return _free_count > 0;
}

TAllocationBlock::~TAllocationBlock() {

    if (_free_count < _count) std::cout << "TAllocationBlock: Memory leak?" << std::endl;
    else std::cout << "TAllocationBlock: Memory freed" << std::endl;
    delete _free_blocks;
    delete _used_blocks;
}




